package com.tanhua.sso.service;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.vo.PicUploadResult;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * 用户信息服务层
 */
@Slf4j
@Service
public class UserInfoService {

    @Autowired
    private UserService userService;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private FaceEngineService faceEngineService;

    @Autowired
    private PicUploadService picUploadService;

    public Boolean savaUserInfo(Map<String, String> param, String token) {
        //校验token:

        User user = userService.queryUserByToken(token);
        //如果通过token查不到user,则返回null;
        if (user == null) {
            return false;
        }

        System.out.println(param);

        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setSex(StringUtils.equals(param.get("gender"), "man") ? SexEnum.MAN : SexEnum.WOMAN);
        userInfo.setNickName(param.get("nickname"));
        userInfo.setBirthday(param.get("birthday"));
        userInfo.setCity(param.get("city"));

        //调用userInfoMapper插入数据库：
        int insert = userInfoMapper.insert(userInfo);

        return insert == 1;

    }

    public Boolean saveLogo(MultipartFile file, String token) {
        //校验token:
        User user = userService.queryUserByToken(token);
        if (user == null) {
            return false;
        }

        //token 有效：进行头像人像校验：
        try {
            boolean b = faceEngineService.checkIsPortrait(file.getBytes());
            if (!b) {
                return false;   //不是人像，直接返回false
            }
        } catch (IOException e) {
            log.error("图片校验失败！" + e);
            e.printStackTrace();
        }

        //校验ok,进行上传阿里云文件系统：
        PicUploadResult uploadResult = picUploadService.upload(file);

        if (uploadResult.getName() == null) {  //上传失败，
            return false;
        }

        //上传成功：
        UserInfo userInfo = new UserInfo();
        userInfo.setLogo(uploadResult.getName());

        //更新插入数据库：
        UpdateWrapper<UserInfo> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("user_id", user.getId());
        int update = userInfoMapper.update(userInfo, updateWrapper);

        return update == 1;
    }
}
